//
//  UITextField+ClearButton.m
//  meizhuang
//
//  Created by sky on 16/9/7.
//  Copyright © 2016年 netease. All rights reserved.
//

#import <BlocksKit/BlocksKit+UIKit.h>
#import <Masonry/Masonry.h>

#import "UITextField+ClearButton.h"

@implementation UITextField(ClearButton)

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (void)customizeClearButton {
    self.rightViewMode = UITextFieldViewModeNever;
    self.clearButtonMode = UITextFieldViewModeNever;

    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 36, 36)];
    UIButton *clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [clearButton setImage:[UIImage imageNamed:@"icon_textfield_clear"] forState:UIControlStateNormal];
    @weakify(self);
    [clearButton bk_whenTapped:^{
        @strongify(self);
        self.text = @"";
        [[NSNotificationCenter defaultCenter] postNotificationName:UITextFieldTextDidChangeNotification object:self];
    }];
    [rightView addSubview:clearButton];
    [clearButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(clearButton.superview);
    }];
    self.rightView = rightView;
    
    [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        @strongify(self);
        [self updateClearButtonState];
    }];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:UITextFieldTextDidBeginEditingNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
        @strongify(self);
        [self updateClearButtonState];
    }];
}

- (void)updateClearButtonState {
    if (self.text.length == 0) {
        self.rightViewMode = UITextFieldViewModeNever;
    } else {
        self.rightViewMode = UITextFieldViewModeWhileEditing;
    }
}

@end
